package com.yueqianshop.seckill.sevice.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.yueqianshop.common.to.SeckillOrderTo;
import com.yueqianshop.common.utils.R;
import com.yueqianshop.common.vo.MemberRespVo;
import com.yueqianshop.seckill.constant.SeckillConstant;
import com.yueqianshop.seckill.feign.CouponFeignService;
import com.yueqianshop.seckill.feign.ProductFeignService;
import com.yueqianshop.seckill.interceptor.LoginUserInterceptor;
import com.yueqianshop.seckill.sevice.SeckillService;
import com.yueqianshop.seckill.vo.SeckillSessionsWithSkusVo;
import com.yueqianshop.seckill.vo.SeckillSkuRedisTo;
import com.yueqianshop.seckill.vo.SkuinfoVo;

import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Service
public class SeckillServiceImpl implements SeckillService {

    @Autowired
    CouponFeignService couponFeignService;
    
    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    RedissonClient redissonClient;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Override
    public void uploadSeckillSkuLatest3Days() {
        R r = couponFeignService.getLates3DaysSession();
        List<SeckillSessionsWithSkusVo> sessionData = r.getData(new TypeReference<List<SeckillSessionsWithSkusVo>>() {
        });
        if (r != null && sessionData != null) {
            saveSessionInfos(sessionData);
            saveSessionSkuInfos(sessionData);

        }
    }

    /**
     * 缓存秒杀活动关联的商品信息
     *
     * @param data
     */
    private void saveSessionSkuInfos(List<SeckillSessionsWithSkusVo> data) {
        data.stream().forEach(session -> {
            BoundHashOperations<String, Object, Object> ops = redisTemplate.boundHashOps(SeckillConstant.SECKILL_SKUS_CACHE_PREFIX);
            session.getSeckillSkuRelationEntities().stream().forEach(sku -> {
                String s = sku.getPromotionSessionId().toString()+"-"+sku.getSkuId().toString();
                //如果当前场次秒杀商品没有在redis中再进行上架
                if(!ops.hasKey(s)){
                    SeckillSkuRedisTo seckillSkuRedisTo = new SeckillSkuRedisTo();
                    R r = productFeignService.getSkuInfo(sku.getSkuId());
                    if(r.getCode() == 0){
                        //1.sku基本信息
                        SkuinfoVo skuInfo = r.getData("skuInfo", new TypeReference<SkuinfoVo>() {
                        });
                        seckillSkuRedisTo.setSkuinfoVo(skuInfo);
                    }
                    // 2、sku秒杀信息
                    BeanUtils.copyProperties(sku, seckillSkuRedisTo);

                    // 3、秒杀时间信息
                    seckillSkuRedisTo.setStartTime(session.getStartTime().getTime());
                    seckillSkuRedisTo.setEndTime(session.getEndTime().getTime());

                    //4 、商品秒杀随机码，防止秒杀接口暴露，被恶意攻击
                    String token = UUID.randomUUID().toString().replace("-","");
                    seckillSkuRedisTo.setRandomCode(token);
                    //5、秒杀商品库存的分布式信号量
                    RSemaphore semaphore = redissonClient.getSemaphore(SeckillConstant.SECKILL_SKU_STOCK_SEMAPHORE + token);
                    semaphore.trySetPermits(100);
                    ops.put(sku.getPromotionSessionId().toString()+"-"+sku.getSkuId().toString(), JSON.toJSONString(seckillSkuRedisTo));


                }
            });
        });







    }

    /**
     * 缓存秒杀活动信息
     *
     * @param data
     */
    private void saveSessionInfos(List<SeckillSessionsWithSkusVo> data) {
        if (data != null) {
            data.stream().forEach(session -> {
                //时间转为long值 方便比较
                long startTime = session.getStartTime().getTime();
                long endTime = session.getEndTime().getTime();
                // 活动的开始时间+"_"+结束时间作为key
                String key = SeckillConstant.SECKILL_SESSION_CACHE_PREFIX + startTime + "_" + endTime;
                Boolean hasKey = redisTemplate.hasKey(key);
                if (!hasKey) {
                    // 活动场次id+"-"+活动关联的所有商品的skuId作为value
                    List<String> value = session.getSeckillSkuRelationEntities().stream()
                            .map(item -> item.getPromotionSessionId().toString() + "-" + item.getSkuId().toString()).collect(Collectors.toList());
                    redisTemplate.opsForList().leftPushAll(key, value);
                }
            });
        }
    }


    /**
     * 获取当前时间需要参与秒杀活动的商品
     * @return
     */
    @Override
    public List<SeckillSkuRedisTo> getCurrentSeckillSku() {
        List<SeckillSkuRedisTo> result = null;
        //1、确定当前时间属于哪个场次
        long now = new Date().getTime();
        Set<String> keys = redisTemplate.keys(SeckillConstant.SECKILL_SESSION_CACHE_PREFIX + "*");
        for (String key : keys) {
            String[] time = key.replace(SeckillConstant.SECKILL_SESSION_CACHE_PREFIX, "").split("_");
            Long startTime = Long.parseLong(time[0]);
            Long endTime = Long.parseLong(time[1]);
            if (now >= startTime) {
                //2、获取场次需要的商品信息
                //获取当前场次和其对应的所有商品的skuId
                List<String> session = redisTemplate.opsForList().range(key, -100, 100);
                BoundHashOperations<String, String, String> ops = redisTemplate.boundHashOps(SeckillConstant.SECKILL_SKUS_CACHE_PREFIX);
                List<String> seckillSkus = ops.multiGet(session);
                if (seckillSkus != null && seckillSkus.size() > 0) {
                    List<SeckillSkuRedisTo> seckillSkuRedisTos = seckillSkus.stream().map(sku -> {
                        return JSON.parseObject(sku, SeckillSkuRedisTo.class);
                    }).collect(Collectors.toList());
                    result = seckillSkuRedisTos;
                    break;
                }
                break;
            }
        }

        return result;
    }

    /**
     * 根据skuId获取秒杀商品信息
     * @param skuId
     * @return
     */
    @Override
    public SeckillSkuRedisTo getSkuSeckillInfo(Long skuId) {
        //获取所有需要秒杀的key
        BoundHashOperations<String, String, String> ops = redisTemplate.boundHashOps(SeckillConstant.SECKILL_SKUS_CACHE_PREFIX);
        Set<String> keys = ops.keys();
        if(keys != null && keys.size() > 0){
            // 正则表达式  ,表示匹配   数字-skuId
            String regx = "\\d-" + skuId;
            for (String key : keys) {
                if(Pattern.matches(regx, key)){
                    //获取sku信息
                    String skuInfoStrig = ops.get(key);
                    SeckillSkuRedisTo seckillSkuRedisTo = JSON.parseObject(skuInfoStrig, SeckillSkuRedisTo.class);

                    // 当前时间
                    long now = new Date().getTime();
                    // 活动开始时间
                    long startTime = seckillSkuRedisTo.getStartTime();
                    // 活动结束时间
                    long endTime = seckillSkuRedisTo.getEndTime();
                    // 判断当前时间在不在活动范围内
                    if(now < startTime){
                        // 不在活动范围内，随机码不能暴露
                        seckillSkuRedisTo.setRandomCode(null);
                    }

                    return seckillSkuRedisTo;
                }
            }

        }

        return null;
    }

    @Override
    public String seckill(String killId, String key, Integer num) {
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();
        //1、获取当前秒杀商品的详细信息
        BoundHashOperations<String, String, String> ops = redisTemplate.boundHashOps(SeckillConstant.SECKILL_SKUS_CACHE_PREFIX);
        String skuInfoString = ops.get(killId);
        if(!StringUtils.isEmpty(skuInfoString)){
            // 2、检验合法性
            SeckillSkuRedisTo skuTo = JSON.parseObject(skuInfoString, SeckillSkuRedisTo.class);
            long endTime = skuTo.getEndTime();
            long startTime = skuTo.getStartTime();
            long now = new Date().getTime();
            // 2.1 、检验时间合法性
            if(now >= startTime){
                String killId2 = skuTo.getPromotionSessionId() + "-" +skuTo.getSkuId();
                String randomCode = skuTo.getRandomCode();
                // 2.2、检验随机码和商品Id
                if (killId.equals(killId2) && key.equals(randomCode)){
                    // 2.3、检验秒杀商品的数量
                    if(num <= Integer.parseInt(skuTo.getSeckillLimit().toString()));{
                        // 2.4、检验是否购买过
                        String isBuyKey = memberRespVo.getId().toString() + "-" + killId;
                        Boolean isNotBuy = redisTemplate.opsForValue().setIfAbsent(isBuyKey, num.toString(), now, TimeUnit.MINUTES);
                        if(isNotBuy){// 未购买过
                            // 3、获取信号量
                            RSemaphore semaphore = redissonClient.getSemaphore(SeckillConstant.SECKILL_SKU_STOCK_SEMAPHORE + randomCode);
                            boolean b = semaphore.tryAcquire();
                            if(b){
                                // 4、秒杀成功，快速下单，发送信息给MQ
                                SeckillOrderTo seckillOrderTo = new SeckillOrderTo();
                                String orderSn = IdWorker.getTimeId();
                                seckillOrderTo.setOrderSn(orderSn);
                                seckillOrderTo.setPromotionSessionId(skuTo.getPromotionSessionId());
                                seckillOrderTo.setSkuId(skuTo.getSkuId());
                                seckillOrderTo.setSeckillPrice(skuTo.getSeckillPrice());
                                seckillOrderTo.setNum(num);
                                seckillOrderTo.setMemberId(memberRespVo.getId());
                                rabbitTemplate.convertAndSend("order-event-exchange", "order.seckill.order", seckillOrderTo);
                                return orderSn;

                            }
                        }
                    }
                }

            }
        }
        return null;
    }


}